fldmeta_prop.func.ServiceTask = {};
fldmeta_prop.func.ServiceTask.predefined = {};

//on color change of UserTask
fldmeta_prop.func.ServiceTask.onDisplayStyle = function(elemid, rId, nv) {
	if (rId=="displayStyle_GradientColor0") {
		var grd = Snap("svg").select("#Gradient_"+elemid);
		grd && grd.remove();
		var c0 = nv;
		var c1 = fl.curflow.bpmnConfig[elemid]["displayStyle_GradientColor1"]||flstyle.elem.gradients.ServiceTask.b;
		var c2 = fl.curflow.bpmnConfig[elemid]["displayStyle_GradientColor2"]||flstyle.elem.gradients.ServiceTask.c;
		grd = Snap("svg").paper.gradient("L(0, 0, 100, 100)"+c0+"-"+c1+":25-"+c2);
		grd.attr("id", "Gradient_"+elemid);
		Snap("g[data-element-id='"+elemid+"'] g.djs-visual rect").attr({"fill" : "url(#Gradient_"+elemid+")"});
	} else if (rId=="displayStyle_GradientColor1") {
		var grd = Snap("svg").select("#Gradient_"+elemid);
		grd && grd.remove();
		var c0 = fl.curflow.bpmnConfig[elemid]["displayStyle_GradientColor0"]||flstyle.elem.gradients.ServiceTask.a;
		var c1 = nv;
		var c2 = fl.curflow.bpmnConfig[elemid]["displayStyle_GradientColor2"]||flstyle.elem.gradients.ServiceTask.c;
		grd = Snap("svg").paper.gradient("L(0, 0, 100, 100)"+c0+"-"+c1+":25-"+c2);
		grd.attr("id", "Gradient_"+elemid);
		Snap("g[data-element-id='"+elemid+"'] g.djs-visual rect").attr({"fill" : "url(#Gradient_"+elemid+")"});
	} else if (rId=="displayStyle_GradientColor2") {
		var grd = Snap("svg").select("#Gradient_"+elemid);
		grd && grd.remove();
		var c0 = fl.curflow.bpmnConfig[elemid]["displayStyle_GradientColor0"]||flstyle.elem.gradients.ServiceTask.a;
		var c1 = fl.curflow.bpmnConfig[elemid]["displayStyle_GradientColor1"]||flstyle.elem.gradients.ServiceTask.b;
		var c2 = nv;
		grd = Snap("svg").paper.gradient("L(0, 0, 100, 100)"+c0+"-"+c1+":25-"+c2);
		grd.attr("id", "Gradient_"+elemid);
		Snap("g[data-element-id='"+elemid+"'] g.djs-visual rect").attr({"fill" : "url(#Gradient_"+elemid+")"});
	} else if (rId=="displayStyle_BorderEffect") {
		if (nv=='none' || !nv) {
			Snap("g[data-element-id='"+elemid+"'] g.djs-visual rect").attr("filter", null);
		} else {
			Snap("g[data-element-id='"+elemid+"'] g.djs-visual rect").attr("filter","url(#"+nv+")");
		}
	} else if (rId=="displayStyle_BorderStrokeWidth") {
		Snap("g[data-element-id='"+elemid+"'] g.djs-visual rect").attr({"strokeWidth" : parseInt(nv)});
	} else if (rId=="displayStyle_BorderColor") {
		Snap("g[data-element-id='"+elemid+"'] g.djs-visual rect").attr({"stroke" : nv});
	} else if (rId=="displayStyle_ActivityIconColor") {
		Snap("g[data-element-id='"+elemid+"'] g.djs-visual").selectAll("path").forEach(function(el){
			el.attr({"stroke" : nv || "#000000"});
		});
	} else if (rId=="displayStyle_fontColor") {
		Snap("g[data-element-id='"+elemid+"'] g.djs-visual text").attr({"fill" : nv || "#000000"});
	}
};

//选择Rest服务
fldmeta_prop.func.ServiceTask.selectService = function(rId, cId) {
	var w1 = fm_createCenterWindow('wid_selectService', fmd_i18n_prop_selectService, 800, 600);
	
	var lo1 = w1.attachLayout("3U");
	lo1.cells('a').hideHeader();
	lo1.cells('b').hideHeader();
	lo1.cells('c').hideHeader();
	lo1.cells('a').setWidth(330);
	lo1.cells('c').setHeight(50);
	var stb1 = lo1.cells('a').attachStatusBar();
	stb1.setText("<div id='id_paging_selectService1'></div>");
	
	var str2 = [{ type:"block" , name:"form_block_1", offsetLeft:(dhx_skin=="dhx_web"?"333":"340"), offsetTop:"0", list:[
		   		{ type:"button" , name:"fb_ok", value:fmd_i18n_b_ok, inputTop:0}]}];
	var fm2 = lo1.cells('c').attachForm(str2);
	var svcq = {};
	svcq.rest_get = flvar.fmdCtx + "/rest/service/";
	svcq.rest_query = flvar.fmdCtx + "/rest/service/query";
	
	//grid
	var ragrid = lo1.cells('a').attachGrid();
	ragrid.setHeader([fmd_i18n_l_no,
	                  'ID',
	                  fmd_i18n_prop_svc_desc,
	                  fmd_i18n_prop_svc_uri],
	                    null,
	                    ["text-align:center;",
	                     "text-align:center;",
	                     "text-align:center;",
	                     "text-align:center;"]);
	ragrid.attachHeader("#rspan,#rspan,<input id='sr_desc' type='text' style='width:90%'/>,<input id='sr_uri' type='text' style='width:90%'/>");
	ragrid.setInitWidths("60,100,245,300");
	ragrid.setColumnIds("NO,ID,DESC,URI");
	ragrid.setColTypes("ro,ro,ro,ro");
	ragrid.setColSorting("int,str,str,str");
	ragrid.setColumnsVisibility("false,true,false,true");
	ragrid.setColAlign("center,left,left,left");
	ragrid.setEditable(false);
	ragrid.setLang(fl.lang);
	ragrid.init();
	ragrid._grid_ordercolumns = [{"CREATE_TIME":"DESC"}];
	
	//paging
	ragrid.setPagingWTMode(true,true,true,[20,50,100]);
	ragrid.enablePaging(true,20,5,'id_paging_selectService1');
	ragrid.setPagingSkin("toolbar", dhx_skin);
	
	ragrid.attachEvent("onPageChanged", function(ind,fInd,lInd){
		svc_toPage(fInd+1, lInd);
	});
	
	//header click event
	ragrid.attachEvent("onHeaderClick", grid_onHeaderClick);
	
	//onselect row
	ragrid.attachEvent("onSelectStateChanged", function(rid) {
		if (!rid) return;
		var svcid = ragrid.cells(rid, 1).getValue();
		initSvcDetail(svcid);
	});
	
	//bind searcher event
	//disable onclick order by function for this header
	var trsr_type = $("#sr_desc").parents('tr:first');
	trsr_type.find('td').bind('click',fl_stopEvent);
	trsr_type.find('td').bind('mouseover',fl_stopEvent);
	$("#sr_desc").bind('keypress', dict_enterQuery);
	$("#sr_uri").bind('keypress', dict_enterQuery);
	
	fm2.attachEvent("onButtonClick", function(btid) {
		if (btid=='fb_ok') {
			var rid = ragrid.getSelectedRowId();
			if (!rid) {
				msg(fmd_i18n_msg_sel);
				return;
			}
			var id = ragrid.cells(rid, 1).getValue();
			var desc = ragrid.cells(rid, 2).getValue();
			var newval = {"realValue":id, "displayValue":desc};
			
			//get vars
			var idxVARNAME = svcq.vargrid.getColIndexById("VARNAME"), 
			idxVARTYPE = svcq.vargrid.getColIndexById("VARTYPE"), 
			idxVARDESC = svcq.vargrid.getColIndexById("VARDESC"),
			idxDEFAULT = svcq.vargrid.getColIndexById("DEFAULT");
			var rn = svcq.vargrid.getRowsNum();
			if (rn>0) {
				intfvars = [];
				for (var i=0; i<rn; i++) {
					var varname = $.trim(svcq.vargrid.cellByIndex(i, idxVARNAME).getValue());
					var vartype = svcq.vargrid.cellByIndex(i, idxVARTYPE).getValue();
					var vardesc = $.trim(svcq.vargrid.cellByIndex(i, idxVARDESC).getValue());
					var vardv = $.trim(svcq.vargrid.cellByIndex(i, idxDEFAULT).getValue());
					var rd = {"varname":varname, "vartype":vartype, "vardesc":vardesc, "default":vardv};
					if (vardv!=undefined && vardv!="") {
						if (vartype=="datetime" && !dhtmlxValidation.isValidDatetimeSS(vardv)) {
							msg(fmd_i18n_elsvc_input+"["+varname+"] : " + fmd_i18n_msg_wrongformatdefaultvalue);
							return;
						} else if (vartype=="int" && !dhtmlxValidation.isValidInteger(vardv)) {
							msg(fmd_i18n_elsvc_input+"["+varname+"] : " + fmd_i18n_msg_wrongformatdefaultvalue);
							return;
						} else if (vartype=="number" && !dhtmlxValidation.isValidNumeric(vardv)) {
							msg(fmd_i18n_elsvc_input+"["+varname+"] : " + fmd_i18n_msg_wrongformatdefaultvalue);
							return;
						} else if (vartype=="json" && !dhtmlxValidation.isValidJsonstr(vardv)) {
							msg(fmd_i18n_elsvc_input+"["+varname+"] : " + fmd_i18n_msg_wrongformatdefaultvalue);
							return;
						}
					}
					intfvars.push(rd);
				}
				newval.intfvars = intfvars;
			}
			
			fmdc.grid_prop.cells(rId, cId).setValue(newval, true);	//第二个参数必须为true，触发事件
			w1.close();
		}
	});
	
	svc_toPage(1, 20);
	
	//query version
	function svc_toPage(fromRow, toRow){
		lo1.progressOn();
		var p = {"args":{"target":"BPM","category":"ENUMERATION"}, "fromRow":fromRow, "toRow":toRow, "timezoneOffset":new Date().getTimezoneOffset(),
				"ordercolumns":JSON.stringify(ragrid._grid_ordercolumns)};
		
		var p = {"queryParams":{}, "fromRow":fromRow, "toRow":toRow, "timezoneOffset":new Date().getTimezoneOffset(),
				"ordercolumns":JSON.stringify(ragrid._grid_ordercolumns)};
		if (svcq.vquery_desc) {
			p.queryParams.svcDesc = svcq.vquery_desc;
		}
		if (svcq.vquery_uri) {//TODO
			p.queryParams.svcConfig = {"uri":svcq.vquery_uri};
		}
		p.queryParams = JSON.stringify(p.queryParams);
		var ret = doPostSyncJson(svcq.rest_query, p);
		if (!ret) {
			lo1.progressOff();
			msgErr(fmd_i18n_msg_readfail);
			return;
		}
		ragrid.clearAllInPaging();
		ragrid.parse(ret, "json");
		lo1.progressOff();
	}

	//call query version
	function dict_enterQuery(e) {
		if (e.keyCode==13) {
			svcq.vquery_desc = $.trim($("#sr_desc").val());
			svcq.vquery_uri = $.trim($("#sr_uri").val());
			svc_toPage(1, 10);
		}
	}
	
	function initSvcDetail(svcid) {
		lo1.progressOn();
		
		var lod = lo1.cells('b').attachLayout('2E');
		lod.cells('a').setText(fmd_i18n_elsvc_basic);
		lod.cells('a').setHeight(120);
		lod.cells('b').setText(fmd_i18n_elsvc_input);
		
		//basic form
		var str1 = [
			   		{ type:"input" , name:"uri", label:fmd_i18n_elsvc_uri, labelWidth:100, inputWidth:400, readonly:true, offsetLeft:"10", offsetTop:"10", position:"label-top"  }
			   	];
		svcq.fm = lod.cells('a').attachForm(str1);
		
		var svc = doGetSyncJson(svcq.rest_get + svcid);
		if (!svc) {
			lo1.progressOff();
			msgErr(fmd_i18n_msg_readfail);
			return;
		}
		
		if (svc.svcConfig && svc.svcConfig.uri) {
			svcq.fm.setItemValue("uri", svc.svcConfig.uri);
		}
		
		svcq.vargrid && svcq.vargrid.destructor && svcq.vargrid.destructor();
		svcq.vargrid=null;
		svcq.vargrid = lod.cells('b').attachGrid();
		svcq.vargrid.setIconsPath(fl.imagepath);
		svcq.vargrid.setHeader([fmd_i18n_elsvc_hd_name,
		                        fmd_i18n_elsvc_hd_type,
		                        fmd_i18n_elsvc_hd_desc,
		                        fmd_i18n_elsvc_hd_default],
		                    null,
		                    ["text-align:center;",
		                     "text-align:center;",
		                     "text-align:center;",
		                     "text-align:center;"]);
		svcq.vargrid.setInitWidths("100,100,150,120");
		svcq.vargrid.setColumnIds("VARNAME,VARTYPE,VARDESC,DEFAULT");
		svcq.vargrid.setColTypes("ro,pairro,ro,ed");
		svcq.vargrid.setColSorting("na,na,na,na");
		svcq.vargrid.setColumnsVisibility("false,false,false,false");
		svcq.vargrid.setColAlign("left,left,left,right");
		svcq.vargrid.setEditable(true);
		svcq.vargrid.enableEditEvents(true,true);
		svcq.vargrid.enableValidation(true,true);
		svcq.vargrid.setLang(fl.lang);
		svcq.vargrid.init();
		
		//load vars
		var p = "input";
		if (svc.svcConfig && svc.svcConfig.intfvars && svc.svcConfig.intfvars[p] && svc.svcConfig.intfvars[p].length) {
			for (var i=0; i<svc.svcConfig.intfvars[p].length; i++) {
				var rd = [svc.svcConfig.intfvars[p][i].varname, 
                          svc.svcConfig.intfvars[p][i].vartype +pairro_spliter+ fmd_i18n_enusvc_vartypes[svc.svcConfig.intfvars[p][i].vartype], 
                          svc.svcConfig.intfvars[p][i].vardesc];
				rd.push(svc.svcConfig.intfvars[p][i]["default"]);
				svcq.vargrid.addRow(i+1, rd);
			}
		}
		
		lo1.progressOff();
	}
};

//set data mapping 数据映射
fldmeta_prop.func.ServiceTask.predefined["dataMapping"] = {
    	"name" : fmd_i18n_prop_dataMapping,
    	"img" : "dataMapping.png",
    	"tooltip" : fmd_i18n_tooltip_dataMapping,
    	"cellType" : {
    		"type" : "btnex",
    		"config" : {
				"onclick" : fldmeta_prop.func.callSetDataMapping
			}
    	},
    	"value" : {"default":null},
    	"validatorFunc" : function(elemid, val, prefix) {
    		//验证是异步的，必须返回后再弹出验证信息
    		fldmeta_prop.func.getActivityVarsAndCheckValWithCallback(elemid, val, function(elemid, val, activityVars) {
    			if (!activityVars) return;
    			if (!val || MyUtilJs.isEmpty(val)) {
					/*if (!MyUtilJs.isEmpty(activityVars.input) || !MyUtilJs.isEmpty(activityVars.output)) {
						fl_pushValidationErr(elemid, "dataMapping", "warning", prefix + fmd_i18n_msg_noDatamapping);
					}*/
				} else {
					//检查映射的表单变量和流程变量是否有效
					for (var io in val) {
						for (var fv in val[io]) {
							//表单变量
							var fva = fv.split("|");
							var ioname = io=="input" ? fmd_i18n_title_dataMapping_input : fmd_i18n_title_dataMapping_output;
							try {
								var b1 = eval("activityVars[io][fva[0]].children[fva[1]]!=undefined");
								if (!b1) fl_pushValidationErr(elemid, "dataMapping", "error", prefix + 
										ioname + fmd_i18n_msg_invalidbindingformvar +fva[0]+"."+fva[1] + fmd_i18n_msg_reconfigdm); 
							}catch(e){
								fl_pushValidationErr(elemid, "dataMapping", "error", prefix + 
										ioname + fmd_i18n_msg_invalidbindingformvar +fva[0]+"."+fva[1] + fmd_i18n_msg_reconfigdm);
							}
							//流程变量
							if (!fldmeta_prop.func.isValidProcessVar(val[io][fv])) {
								fl_pushValidationErr(elemid, "dataMapping", "error", prefix + 
										ioname + fmd_i18n_msg_invalidmappingpvar +val[io][fv]);
							}
						}
					}
				}
    		});
    	}
    };

//properties settings for ServiceTask
fldmeta_prop.control.ServiceTask = {
		"includes-properties" : {
			"common" : fldmeta_prop.common.all.properties,
			"activitycommon" : fldmeta_prop.common.activity.properties
		},
		"properties" : {
			"service" : {
				"name" : fmd_i18n_prop_service,
		    	"cellType" : {
		    		"type" : "btnex",
					"config" : {
                        "displayValue": "displayValue",
	    				"onclick" : fldmeta_prop.func.ServiceTask.selectService,
                        "ishidebtn": function () {
                            return !fmdc.grid_prop.isEditor
                        }
	    			}
		    	},
		    	"img" : "service.png",
		    	"value" : {"default":{}},
		    	"clearAfterChange" : ["dataMapping"],
		    	"sub" : {
		    		"dataMapping" : fldmeta_prop.func.ServiceTask.predefined["dataMapping"]
		    	}
			}
		},
		"abandon-properties" : function() {
			var abps = fldmeta_prop.func.getAbandonPropertiesForConditional();
			if (!abps) {
				return ["tiprow_activitycommon"];
			} else {
				abps.push("tiprow_activitycommon");
			}
			return abps;
		},
		"styles" : {
    		"displayStyle" : {
				"name" : fmd_i18n_prop_tip_customstyle,
				"img" : "css.png",
		    	"cellType" : {
		    		"type" : "coro",
		    		"options" : fmd_i18n_prop_displayStyle_vals
		    	},
		    	"value" : {"default":"theme"},
		    	"conditional-sub" : {
		    		"custom" : {
		    			"displayStyle_GradientColor0" : {
		        			"name" : fmd_i18n_prop_color0,
		    		    	"cellType" : "cp",
		    		    	"img" : "color.png",
		    		    	"value" : function() {return flstyle.elem.gradients.ServiceTask.a}
		        		},
		    			"displayStyle_GradientColor1" : {
		        			"name" : fmd_i18n_prop_color1,
		    		    	"cellType" : "cp",
		    		    	"img" : "color.png",
		    		    	"value" : function() {return flstyle.elem.gradients.ServiceTask.b}
		        		},
		        		"displayStyle_GradientColor2" : {
		        			"name" : fmd_i18n_prop_color2,
		    		    	"cellType" : "cp",
		    		    	"img" : "color.png",
		    		    	"value" : function() {return flstyle.elem.gradients.ServiceTask.c}
		        		},
		        		"displayStyle_ActivityIconColor" : function() {
		    				var obj1 = MyUtilJs.copyObj(fldmeta_prop.common.predefined["displayStyle_ActivityIconColor"]);
		    				obj1.value["default"] = flstyle.elem.defaultActivityIconColor;
		    				return obj1;
		    			},
		        		"displayStyle_fontColor" : function() {
		    				var obj1 = MyUtilJs.copyObj(fldmeta_prop.common.predefined["displayStyle_fontColor"]);
		    				obj1.value["default"] = flstyle.elem.defaultFontColor;
		    				return obj1;
		    			},
		        		"displayStyle_BorderStrokeWidth" : function() {
		    				var obj1 = MyUtilJs.copyObj(fldmeta_prop.common.predefined["displayStyle_BorderStrokeWidth"]);
		    				obj1.value["default"] = flstyle.elem.attrs.servicetask.strokeWidth;
		    				return obj1;
		    			},
		        		"displayStyle_BorderColor" : function() {
		    				var obj1 = MyUtilJs.copyObj(fldmeta_prop.common.predefined["displayStyle_BorderColor"]);
		    				obj1.value["default"] = flstyle.elem.attrs.servicetask.stroke;
		    				return obj1;
		    			},
		        		"displayStyle_BorderEffect" : fldmeta_prop.common.predefined["displayStyle_BorderEffect"]
		    		}
		    	}
			}
		},
		"onApply" : function() {
		},
		"propDhxGridEvents" : {
			"onCellChanged" : function(rId,cId,nv) {
				fldmeta_prop.func.onCellChanged_common(rId,cId,nv,
						JSONSelect.match("."+rId, fldmeta_prop.control.ServiceTask));
				fldmeta_prop.func.onCellChanged_stylecommon(rId,cId,nv);
			}
		}
	};


